package com.molichuxing.gateway.api.services.impl;

import com.molichuxing.framework.dto.Paged;
import com.molichuxing.framework.exception.BizException;
import com.molichuxing.framework.result.ResponseCodeEnum;
import com.molichuxing.framework.result.ResponseResult;
import com.molichuxing.gateway.api.services.GoodsApiService;
import com.molichuxing.gateway.bff.basic.entity.response.VehicleMakeVo;
import com.molichuxing.gateway.bff.goods.entity.response.*;
import com.molichuxing.gateway.bff.goods.services.GoodsBffService;
import com.molichuxing.gateway.bff.user.entity.response.UserVo;
import com.molichuxing.gateway.utils.redis.TokenUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 订单相关接口
 * 
 * @author xuelin yi
 * @date 2019年8月11日
 *
 */
@Api(tags = "商品相关接口")
@RestController
@RequestMapping(value = "/goods")
public class GoodsApiServiceImpl extends RootApiService implements GoodsApiService {
	private static final Logger logger = LoggerFactory.getLogger(GoodsApiServiceImpl.class);

	@Resource
	private TokenUtil tokenUtil;

	@Resource
	private GoodsBffService goodsBffService;

	@Override
	@ApiOperation(value = "根据商品id判断商品是否禁售")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "storeId", value = "门店id", required = true, dataType = "Integer"),
			@ApiImplicitParam(name = "goodsId", value = "商品id", required = true, dataType = "Integer"),
	})
	@GetMapping(value = "/prohibited")
	public ResponseResult<Boolean> isProhibited(@RequestParam Integer goodsId, @RequestParam Integer storeId) throws Exception {
		ResponseResult<Boolean> result = new ResponseResult<>();
		try {
			return result.success(goodsBffService.isProhibited(goodsId, storeId));
		} catch (BizException e) {
			result.error(e.getExceptionCode() == null ? ResponseCodeEnum.UNKNOWN_ERROR.getCode() : e.getExceptionCode(),
					e.getMessage());
		} catch (Exception e) {
			logger.error("[isProhibited]根据商品id判断商品是否禁售异常", e);
			result.error("根据商品id判断商品是否禁售异常");
		}
		return result;
	}

	/**
	 * 获取商品列表信息
	 * @param
	 * @return
	 */
	@Override
	@ApiOperation(value = "获取商品列表信息")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "storeId", value = "门店id", required = true, dataType = "Integer"),
			@ApiImplicitParam(name = "pageNum", value = "页码", required = true, dataType = "Integer"),
			@ApiImplicitParam(name = "pageSize", value = "每页条数", required = true, dataType = "Integer")

	})
	@GetMapping(value = "/list")
	@Deprecated
	public ResponseResult<Paged<GoodsVo>> getAppGoodsList(@RequestParam Integer storeId, @RequestParam Integer pageNum, @RequestParam Integer pageSize) {
		ResponseResult<Paged<GoodsVo>> result = new ResponseResult<>();
		try {
			return result.success(goodsBffService.getAppGoodsList(storeId, pageNum, pageSize));
		} catch (BizException e) {
			logger.error("[getAppGoodsList]获取商品列表信息异常:", e);
			result.error(e.getExceptionCode() == null ? ResponseCodeEnum.UNKNOWN_ERROR.getCode() : e.getExceptionCode(),
					e.getMessage());
		}  catch (Exception e) {
			logger.error("[goodsList]获取商品列表信息异常", e);
			result.error("获取商品列表信息异常");
		}
		return result;
	}

	@Override
	@ApiOperation(value = "获取商品列表信息")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "storeId", value = "门店id", required = true, dataType = "Integer"),
			@ApiImplicitParam(name = "pageNum", value = "页码", required = true, dataType = "Integer"),
			@ApiImplicitParam(name = "goodsType", value = "1:专属，2：订阅,逗号拼接", required = false, dataType = "String"),
			@ApiImplicitParam(name = "startBudget", value = "开始预算", required = false, dataType = "Integer"),
			@ApiImplicitParam(name = "endBudget", value = "结束预算", required = false, dataType = "Integer"),
			@ApiImplicitParam(name = "startTime", value = "开始时间", required = false, dataType = "Integer"),
			@ApiImplicitParam(name = "endTime", value = "结束时间", required = false, dataType = "Integer"),
			@ApiImplicitParam(name = "pageSize", value = "每页条数", required = true, dataType = "Integer"),
			@ApiImplicitParam(name = "sortFlag", value = "1：全部车型，2：帮您选车，3：日常代步，4：热销车型，5：产品列表", required = false, dataType = "Integer")
	})
	@GetMapping(value = "/list/new")
	public ResponseResult<Paged<GoodsVo>> getAppGoodsListNew(@RequestParam Integer storeId, @RequestParam(required = false) Integer sortFlag, @RequestParam(required = false) String goodsType,
															 @RequestParam(required = false) Integer startBudget,
															 @RequestParam(required = false) Integer endBudget,
															 @RequestParam(required = false) Integer startTime,
															 @RequestParam(required = false) Integer endTime,
															 @RequestParam Integer pageNum, @RequestParam Integer pageSize) {
		ResponseResult<Paged<GoodsVo>> result = new ResponseResult<>();
		try {
			Map<String, Object> selectParam = new HashMap<>();
			if(null != goodsType) {
				selectParam.put("goodsType", goodsType);
			}
			if(null != startBudget) {
				selectParam.put("startBudget", startBudget);
			}
			if(null != endBudget) {
				selectParam.put("endBudget", endBudget);
			}
			if(null != startTime) {
				selectParam.put("startTime", startTime);
			}
			if(null != endTime) {
				selectParam.put("endTime", endTime);
			}
			return result.success(goodsBffService.getAppGoodsListNew(storeId, selectParam, sortFlag, pageNum, pageSize));
		} catch (BizException e) {
			logger.error("[getAppGoodsList]获取商品列表信息异常:", e);
			result.error(e.getExceptionCode() == null ? ResponseCodeEnum.UNKNOWN_ERROR.getCode() : e.getExceptionCode(),
					e.getMessage());
		}  catch (Exception e) {
			logger.error("[goodsList]获取商品列表信息异常", e);
			result.error("获取商品列表信息异常");
		}
		return result;
	}




	@Override
    @ApiOperation(value = "首页-获取商品的热销车型")
    @GetMapping(value = "/sell/well/list")
    public ResponseResult<List<GoodsVo>> getSellWellGoodsList() {
        ResponseResult<List<GoodsVo>> result = new ResponseResult<>();
        try {
            return result.success(goodsBffService.getSellWellGoodsList());
        } catch (Exception e) {
            logger.error("[getSellWellGoodsList]获取商品的热销车型异常", e);
            result.error("获取商品的热销车型异常");
        }
        return result;
    }

    /**
	 * 根据商品id、里程包id获取商品信息
	 * @param
	 * @return
	 */
	@Override
	@ApiOperation(value = "根据商品id、里程包id获取商品信息")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "goodsId", value = "商品id", required = true, dataType = "Integer"),
			@ApiImplicitParam(name = "packageId", value = "里程包id（订阅商品传）", required = false, dataType = "Integer")

	})
	@GetMapping(value = "/detail")
	public ResponseResult<GoodsAppDetailVo> getAppGoods(@RequestParam Integer goodsId,@RequestParam(required = false) Integer packageId) {
		ResponseResult<GoodsAppDetailVo> result = new ResponseResult<>();
		try {
			return result.success(goodsBffService.getAppGoods(goodsId, packageId));
		} catch (Exception e) {
			logger.error("[goodsList]获取商品列表信息异常", e);
			result.error("获取商品列表信息异常");
		}
		return result;
	}

	@Override
	@ApiOperation(value = "根据商品id获取专属商品抽屉")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "goodsId", value = "商品id", required = true, dataType = "Integer"),
			@ApiImplicitParam(name = "storeId", value = "门店id", required = true, dataType = "Integer")

	})
	@GetMapping(value = "/exclusive/drawer/detail")
	public ResponseResult<GoodsExclusiveDrawerVo> getAppExclusiveGoods(@RequestParam Integer goodsId, @RequestParam Integer storeId) throws Exception {
		ResponseResult<GoodsExclusiveDrawerVo> result = new ResponseResult<>();
		try {
			return result.success(goodsBffService.getAppExclusiveGoods(goodsId, storeId));
		} catch (Exception e) {
			logger.error("[getAppExclusiveGoods]根据商品id获取专属商品抽屉异常", e);
			result.error("根据商品id获取专属商品抽屉异常");
		}
		return result;
	}

	@Override
	@ApiOperation(value = "根据商品id获取订阅商品抽屉")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "goodsId", value = "商品id", required = true, dataType = "Integer"),
			@ApiImplicitParam(name = "packageId", value = "里程包id", required = true, dataType = "Integer"),
			@ApiImplicitParam(name = "storeId", value = "门店id", required = true, dataType = "Integer")
	})
	@GetMapping(value = "/subscribe/drawer/detail")
	public ResponseResult<GoodsSubscribeDrawerVo> getAppSubscribeGoods(@RequestParam Integer goodsId, @RequestParam Integer packageId, @RequestParam Integer storeId) throws Exception {
		ResponseResult<GoodsSubscribeDrawerVo> result = new ResponseResult<>();
		try {
			return result.success(goodsBffService.getAppSubscribeGoods(goodsId, packageId, storeId));
		} catch (Exception e) {
			logger.error("[getAppExclusiveGoods]根据商品id获取订阅商品抽屉异常", e);
			result.error("根据商品id获取专属商品抽屉异常");
		}
		return result;
	}

	@Override
	@ApiOperation(value = "根据商品id、里程包id确认订单信息")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "goodsId", value = "商品id", required = true, dataType = "Integer"),
			@ApiImplicitParam(name = "packageId", value = "里程包id（订阅商品传）", required = false, dataType = "Integer")

	})
	@GetMapping(value = "/confirm/detail")
	public ResponseResult<GoodsAppConfirmDetailVo> getAppConfirmGoods(Integer goodsId, Integer packageId) {
		ResponseResult<GoodsAppConfirmDetailVo> result = new ResponseResult<>();
		try {
			return result.success(goodsBffService.getAppConfirmGoods(goodsId, packageId));
		} catch (Exception e) {
			logger.error("[getAppExclusiveGoods]根据商品id获确认订单异常", e);
			result.error("根据商品id获取专属确认订单异常");
		}
		return result;
	}

	@Override
	@ApiOperation(value = "订阅订单续订商品信息")
	@ApiImplicitParams({ @ApiImplicitParam(name = "orderCode", value = "订单号", required = true, dataType = "Long") })
	@GetMapping(value = "/renew")
	public ResponseResult<GoodsRenewVo> goodsRenew(Long orderCode) {
		ResponseResult<GoodsRenewVo> result = new ResponseResult<>();
		try {
			// 根据token获取用户信息
			// UserVo user = tokenUtil.getUser(token);

			result.success(goodsBffService.getGoodsRenew(orderCode));

		} catch (BizException e) {
			logger.error("[goodsRenew]查询订阅订单续订商品信息异常:", e);
			result.error(e.getExceptionCode() == null ? ResponseCodeEnum.UNKNOWN_ERROR.getCode() : e.getExceptionCode(),
					e.getMessage());
		} catch (Exception e) {
			logger.error("[goodsRenew]查询订阅订单续订商品信息异常:", e);
			result.error("查询续订商品信息异常");
		}
		return result;
	}

	@Override
	@ApiOperation(value = "订阅订单加购商品信息")
	@ApiImplicitParams({ @ApiImplicitParam(name = "orderCode", value = "订单号", required = true, dataType = "Long") })
	@GetMapping(value = "/purchase")
	public ResponseResult<GoodsPurchaseVo> goodsPurchase(Long orderCode) {
		ResponseResult<GoodsPurchaseVo> result = new ResponseResult<>();
		try {
			// 根据token获取用户信息
			// UserVo user = tokenUtil.getUser(token);

			result.success(goodsBffService.getGoodsPurchase(orderCode));

		} catch (BizException e) {
			logger.error("[goodsPurchase]查询订阅订单加购商品信息异常:", e);
			result.error(e.getExceptionCode() == null ? ResponseCodeEnum.UNKNOWN_ERROR.getCode() : e.getExceptionCode(),
					e.getMessage());
		} catch (Exception e) {
			logger.error("[goodsPurchase]查询订阅订单加购商品信息异常:", e);
			result.error("查询加购商品信息异常");
		}
		return result;
	}

	@Override
	@ApiOperation(value = "订阅续订确认订单页信息")
	@ApiImplicitParams({ @ApiImplicitParam(name = "orderCode", value = "订单号", required = true, dataType = "Long"),
			@ApiImplicitParam(name = "goodsId", value = "商品id", required = true, dataType = "Integer"),
			@ApiImplicitParam(name = "packageId", value = "里程包id", required = true, dataType = "Integer") })
	@GetMapping(value = "/renew/confirm/info")
	public ResponseResult<GoodsConfirmVo> goodsRenewConfirm(
			@RequestHeader(value = "token", required = true) String token, Long orderCode, Integer goodsId,
			Integer packageId) {
		ResponseResult<GoodsConfirmVo> result = new ResponseResult<>();
		try {
			// 根据token获取用户信息
			UserVo user = tokenUtil.getUser(token);

			result.success(goodsBffService.getGoodsRenewConfirm(user.getUserId(), orderCode, goodsId, packageId));

		} catch (BizException e) {
			logger.error("[goodsRenewConfirm]查询订阅续订确认订单页信息异常:", e);
			result.error(e.getExceptionCode() == null ? ResponseCodeEnum.UNKNOWN_ERROR.getCode() : e.getExceptionCode(),
					e.getMessage());
		} catch (Exception e) {
			logger.error("[goodsRenewConfirm]查询订阅续订确认订单页信息异常:", e);
			result.error("查询确认订单信息异常");
		}

		return result;
	}

	@Override
	@ApiOperation(value = "订阅加购确认订单页信息")
	@ApiImplicitParams({ @ApiImplicitParam(name = "orderCode", value = "订单号", required = true, dataType = "Long"),
			@ApiImplicitParam(name = "goodsId", value = "商品id", required = true, dataType = "Integer"),
			@ApiImplicitParam(name = "packageId", value = "里程包id", required = true, dataType = "Integer") })
	@GetMapping(value = "/purchase/confirm/info")
	public ResponseResult<GoodsConfirmVo> goodsPurchaseConfirm(
			@RequestHeader(value = "token", required = true) String token, Long orderCode, Integer goodsId,
			Integer packageId) {
		ResponseResult<GoodsConfirmVo> result = new ResponseResult<>();
		try {
			// 根据token获取用户信息
			UserVo user = tokenUtil.getUser(token);

			result.success(goodsBffService.getGoodsPurchaseConfirm(user.getUserId(), orderCode, goodsId, packageId));

		} catch (BizException e) {
			logger.error("[goodsPurchaseConfirm]查询订阅加购确认订单页信息异常:", e);
			result.error(e.getExceptionCode() == null ? ResponseCodeEnum.UNKNOWN_ERROR.getCode() : e.getExceptionCode(),
					e.getMessage());
		} catch (Exception e) {
			logger.error("[goodsPurchaseConfirm]查询订阅加购确认订单页信息异常:", e);
			result.error("查询确认订单信息异常");
		}

		return result;
	}

	@Override
	@ApiOperation(value = "根据门店获取门店的品牌信息（大屏）")
	@ApiImplicitParam(name = "storeId", value = "门店id", required = true, dataType = "Integer")
	@GetMapping(value = "/brand/confirm/info")
	public ResponseResult<List<VehicleMakeVo>> getBrandByStoreId(@RequestHeader(value = "storeId", required = true) Integer storeId) {
		ResponseResult<List<VehicleMakeVo>> result = new ResponseResult<>();
		try {
			result.success(goodsBffService.getBrandByStoreId(storeId));
		} catch (BizException e) {
			logger.error("[getBrandByStoreId]根据门店获取门店的品牌信息异常:", e);
			result.error(e.getExceptionCode() == null ? ResponseCodeEnum.UNKNOWN_ERROR.getCode() : e.getExceptionCode(),
					e.getMessage());
		} catch (Exception e) {
			logger.error("[getBrandByStoreId]根据门店获取门店的品牌信息异常:", e);
			result.error("查询续订商品信息异常");
		}
		return result;
	}

	@Override
	@ApiOperation(value = "获取车型列表（大屏）")
	@ApiImplicitParams({ @ApiImplicitParam(name = "storeId", value = "门店id", required = true, dataType = "Integer"),
			@ApiImplicitParam(name = "brandId", value = "品牌id（全部品牌则不传）", required = false, dataType = "Integer")})
	@GetMapping(value = "/big/screen/goods/list")
	public ResponseResult<List<GoodsBigScreenVo>> getBigScreenGoodsList(@RequestHeader(value = "storeId", required = true) Integer storeId,
               @RequestParam (value = "brandId", required = false) Integer brandId) {
		ResponseResult<List<GoodsBigScreenVo>> result = new ResponseResult<>();
		try {
			result.success(goodsBffService.getBigScreenGoodsList(storeId, brandId));
		} catch (BizException e) {
			logger.error("[getBigScreenGoodsList]获取车型列表（大屏）异常:", e);
			result.error(e.getExceptionCode() == null ? ResponseCodeEnum.UNKNOWN_ERROR.getCode() : e.getExceptionCode(),
					e.getMessage());
		} catch (Exception e) {
			logger.error("[getBigScreenGoodsList]获取车型列表（大屏）异常:", e);
			result.error("获取车型列表（大屏）异常");
		}
		return result;
	}


	@Override
	@ApiOperation(value = "根据商品类型获取图片详情")
	@ApiImplicitParam(name = "goodsType", value = "商品类型（1：专属，2：订阅，3：首页）", required = true, dataType = "Integer")
	@GetMapping(value = "/introduce/type/info")
	public ResponseResult<List<GoodsIntroduceVo>> getGoodsIntroduce(@RequestParam(value = "goodsType", required = true) Integer goodsType) {
		ResponseResult<List<GoodsIntroduceVo>> result = new ResponseResult<>();
		try {
			result.success(goodsBffService.getGoodsIntroduce(goodsType));
		} catch (BizException e) {
			logger.error("[getGoodsIntroduce]根据商品类型获取图片详情异常:", e);
			result.error(e.getExceptionCode() == null ? ResponseCodeEnum.UNKNOWN_ERROR.getCode() : e.getExceptionCode(),
					e.getMessage());
		} catch (Exception e) {
			logger.error("[getGoodsIntroduce]根据商品类型获取图片详情异常:", e);
			result.error("根据商品类型获取图片详情异常");
		}
		return result;
	}

}
